#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry

import sys
import os
import logging
import re
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
except:
    pass
import jarryLibs.mayakit.MayaUtils as mu
reload(mu)
import elsLibs.AssetInfoFromFile as elsaif
reload(elsaif)

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class CheckELSAniNameSpace(CheckBase):
    def __init__(self):
        super(CheckELSAniNameSpace, self).__init__()
        pass

    def check_ref_data(self):
        error_namespace = {}
        ref_ns = []
        for ref in pm.listReferences():
            ref_path = ref.path
            ref_ns.append(ref.namespace)
            if ref_path.startswith('Z:/ELS_Project/Assets/') and '/rig/' in ref_path and ref.isLoaded():
                current_namespace = ref.namespace
                rule_namespace = elsaif.AssetInfoFromFile(ref_path).get_namespace
                num_str_find = re.findall(r'\d+\Z', current_namespace)
                more = current_namespace.replace(rule_namespace, '')
                try:
                    int(more)
                    if more.startswith('0'):
                        raise
                except:
                    if current_namespace != rule_namespace:
                        error_namespace[current_namespace] = {'path': ref_path, 'real_namespace': rule_namespace, "has_dag":True, 'dg_children':[]}

        # Get all scene namespaces
        nsList = cmds.namespaceInfo(lon=True)
        nsList = nsList if nsList else []

        # Remove exclude list items
        excludeList = ['UI', 'shared']

        asbList = cmds.ls(type="assembly")

        for asbNode in asbList:
            asbNs = cmds.assembly(asbNode, q=True, rns=True)
            excludeList.append(asbNs)

        [nsList.remove(ns) for ns in excludeList if nsList.count(ns)]
        [nsList.remove(ns) for ns in ref_ns if nsList.count(ns)]
        # print nsList
        for ns in nsList:
            children_count = cmds.ls("%s:*" % ns)
            self.child_nodes = []
            self.namespace_child_nodes(ns)

            dag_children_list = [c for c in self.child_nodes
                                 if cmds.objectType(c) == 'transform' or cmds.objectType(c) == 'shadingEngine']
            if dag_children_list:
                has_dag = True
                dg_children = []
            else:
                has_dag = False
                dg_children = self.child_nodes
            error_namespace[ns] = {'path': '', 'real_namespace': ns, 'has_dag': has_dag, 'dg_children': dg_children}
        return error_namespace

    def namespace_child_nodes(self, ns):
        # 查询名称空间里的内容
        self.child_nodes += cmds.ls("%s:*" % ns)
        # 查询子项名称空间
        ns_list = cmds.namespaceInfo('%s:' % ns, lon=True)
        ns_list = ns_list if ns_list else []
        for c_ns in ns_list:
            # 遍历名称空间
            self.namespace_child_nodes(c_ns)

    def check(self):
        error_namespace = self.check_ref_data()
        # print 'error_namespace', error_namespace
        if error_namespace:
            result_log = u'Error:'
            err = 0
            for ns in error_namespace:
                ns_data = error_namespace[ns]
                if ns_data['path']:
                    err += 1
                    result_log += u'<br>查询到%s这个参考文件的名称空间不符合规则,可修复(%s->%s)!' % (os.path.basename(ns_data['path']),ns,ns_data['real_namespace'])
                elif not ns_data['has_dag']:
                    result_log += u'<br>查询到多余的名称空间:%s,并带%s个dg节点,修复后可删除!' % (ns,len(ns_data['dg_children']))
                else:
                    result_log += '<br><font color=\"#ffaa00\">' + u'查询到多余的名称空间:%s,存在dag节点,需要手动处理' % ns + "</font></br> "
            if err == 0:
                result_log = result_log.replace('Error:', 'Warning:')
        else:
            result_log = u'Succeed:没有问题\n'
        return result_log
    
    def fix(self):
        error_namespace = self.check_ref_data()

        if error_namespace:
            try:
                result_log = u'Succeed:'
                for ns in error_namespace:
                    ns_data = error_namespace[ns]
                    if ns_data['path']:
                        real_namespace = ns_data['real_namespace']
                        # all_ns_list = cmds.namespaceInfo(lon=True)

                        for n in range(10):
                            if n == 0:
                                n = ''
                            new_ns = real_namespace + str(n)

                            if not cmds.namespace(ex=new_ns):
                                pm.namespace(ren=[ns, new_ns])
                                break
                        result_log += u'<br>%s to %s 成功修复名称空间;' % (ns, real_namespace)
                    elif not ns_data['has_dag']:
                        ns_node_list = cmds.ls('%s:*'%ns)
                        if ns_node_list:
                            print 'ns debug:', ns_node_list
                            for n in ns_node_list:
                                cmds.lockNode(n, l=0)
                                cmds.delete(n)

                        mu.del_namespace(ns)
                        result_log += u'移除了名称空间:%s,并删除了%s个dg节点.' % (ns,len(ns_data['dg_children']))
                        pass
                else:
                    result_log += u'没有可修复的名称空间!'
                return result_log
            except:
                return u'Warning:%s没有修复成功!' % error_namespace.keys()
        else:
            result_log = u'Succeed: 没有问题'
            log.info(result_log)
            return result_log
